<?php
/**
 * Created by PhpStorm.
 * User: UEWARE
 * Date: 2019-9-6
 * Time: 15:29:16
 */

namespace App\Http\Controllers\WeChat\Diary\V1\User;

use App\Http\Controllers\WeChat\WeChatController;
use App\Models\TravelsContentModel;
use App\Models\TravelsModel;
use Illuminate\Http\Request;

class TravelsListController extends WeChatController
{
    /**
     * 我的印记列表
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        // 获取
        $data = $request->only('page', 'size');

        $list = TravelsModel::query()
            ->where('user_id', $this->userId)
            ->orderBy('created_at', 'desc')
            ->forpage($data['page'] ?? 1, $data['size'] ?? 10)
            ->get()
            ->toArray();

        $id = array_unique(array_column($list, 'id'));

        $content = TravelsContentModel::query()
            ->whereIn('t_id', $id)
            ->get(['id', 't_id', 'address'])
            ->toArray();

        $content = array_column($content, null, 't_id');

        foreach ($list as &$val) {
            $val['address'] = json_decode($content[$val['id']]['address'], true)['name'];
            $val['created_at'] = date('Y.m.d H:i', $val['created_at']);
        }

        $count = TravelsModel::query()
            ->where('user_id', $this->userId)
            ->count();

        // 组装数据
        $result['list'] = $list;
        $result['count']['page'] = $data['page'] ?? 1;
        $result['count']['size'] = $data['size'] ?? 10;
        $result['count']['total'] = $count;

        return success($result);
    }
}